package cn.kn.sys.service.impl;

import cn.kn.common.model.R;
import cn.kn.sys.dao.UserRoleDao;
import cn.kn.sys.mapper.UserRoleMapper;
import cn.kn.sys.model.UserRole;
import cn.kn.sys.model.UserRoleExample;
import cn.kn.sys.service.UserRoleService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * @author WangJiang
 * @create 2020-12-12 15:10
 */
@Service
@RequiredArgsConstructor
@Data
public class UserRoleServiceImpl extends BaseService implements UserRoleService {

    private final UserRoleMapper userRoleMapper;
    private final UserRoleDao userRoleDao;

    @Override
    public R getRoleIdsByUserId(Long userId) {
        return R.ok(userRoleDao.getRoleIdsByUserId(userId));

    }

    @Transactional
    @Override
    public R save(Long userId, String roleNames, UserRole[] userRole) {
        UserRoleExample example=new UserRoleExample();
        example.createCriteria().andUserIdEqualTo(userId);
        userRoleMapper.deleteByExample(example);

        if("-1".equals(roleNames)){
            roleNames="";
        }else{
            userRoleDao.insertBatch(Arrays.asList(userRole));
        }
        userRoleDao.updateRoleName(roleNames,userId);

        return R.ok();
    }
}
